package org.java.user.service.impl;

import com.alibaba.druid.util.StringUtils;
import org.java.entity.User;
import org.java.user.dao.UserMapper;
import org.java.user.service.UserService;
import org.java.user.utils.CodeUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author WHQ
 * @version 1.0
 * @date 2022-3-10 0010 下午 3:58
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Override
    public Boolean checkUserId(User user) {
        int count = userMapper.selectCount(user);
        System.out.println(count);
        return count>0;
    }
    //注入消息队列的模板
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public void sendToMq(String to) {
        rabbitTemplate.convertAndSend("","send-queue",to);
        System.out.println("消息发送成功");
    }

    @Override
    public Boolean register(User user) {
        //设置用户的注册时间
        user.setCreated(new Date());
        //得到用户的盐
        String salt = CodeUtils.generateSalt();
        //设置用户的盐
        user.setSalt(salt);
        //加密用户的密码
        String password = CodeUtils.md5Hex(user.getPassword(), salt);
        //重新赋值用户密码
        user.setPassword(password);
        int rows = userMapper.insertSelective(user);
        return rows>0;
    }

    @Override
    public User queryUser(String username, String password) {
        //创建user对象封装查询信息
        User user=new User();
        user.setEmail(username);
        //根据用户id查询用户信息，覆盖默认值
        user=userMapper.selectOne(user);
        if (user==null){
            System.out.println("为空");
            return null;
        }
        //不为空,取出盐，判断用户密码是否正确
        String salt = user.getSalt();
        System.out.println(salt);
        String pwd = CodeUtils.md5Hex(password, salt);
        System.out.println(pwd);
        if (StringUtils.equals(pwd,user.getPassword())) {
            //信息一致，返回user对象
            return user;
        }else {
            System.out.println("密码错误");
            return null;
        }
    }
}
